package com.taotao.test2.config;

import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
 * @author wangjin
 * @date 2023年12月01日 15:49
 */
@Component
public class SensitiveWordFilter {
    @Value("${sensitive.word.file-path}")
    private Resource sensitiveWordFile;

    private Set<String> sensitiveWords;
    public SensitiveWordFilter() {
        this.sensitiveWords = loadSensitiveWords();
    }

    private Set<String> loadSensitiveWords() {
        Set<String> words =new HashSet<>();
        try{
            //敏感词文件中加载敏感词
            String content = new String(FileCopyUtils.copyToByteArray(sensitiveWordFile.getInputStream()), "UTF-8");
             String[] wordArray=content.split("\n");
             for(String word: wordArray){
                 words.add(word.trim());
             }
        }catch (Exception e){
            e.getCause();
        }
        return  words;
    }

   public  String filterSensitiveWords(String input){
        List<Term> terms =ToAnalysis.parse(input).getTerms();
        StringBuilder filteredText=new StringBuilder(input);
        for(Term term: terms){
            if(sensitiveWords.contains(term.getName())){
                //将敏感词替换为*
                replaceSensitiveWord(filteredText, term.getName());
            }
        }
        return  filteredText.toString();
   }

    private void replaceSensitiveWord(StringBuilder text, String sensitiveWord) {
        int index=text.indexOf(sensitiveWord);
        while (index !=-1){
            text.replace(index, index + sensitiveWord.length(), "*");
            index = text.indexOf(sensitiveWord, index + 1);
        }
    }
}
